<template>
  <div class="blog-toc-container">
    <h2>目录</h2>
    <RightList :list="tocWithSelect" @select="handleSelect"></RightList>
  </div>
</template>

<script>
import RightList from "./RightList";
import { deBounce } from "@/utils";
export default {
  props: {
    toc: {
      type: Array,
    },
  },
  data() {
    return {
      activeAnchor: "",
    };
  },
  components: {
    RightList,
  },
  created() {
    this.setSelectDebounce = deBounce(this.setSelect, 50);
    this.$eventBus.$on("mainScroll", this.setSelectDebounce);
  },
  mounted() {
    const hash = location.hash;
    location.hash = "";
    setTimeout(() => {
      location.hash = hash;
    }, 50);
    // location.hash = hash;
  },
  destroyed() {
    this.$eventBus.$off("mainScroll", this.setSelectDebounce);
  },
  computed: {
    tocWithSelect() {
      let getTOC = (toc = []) => {
        return toc.map((r) => ({
          ...r,
          isSelected: r.anchor === this.activeAnchor,
          children: getTOC(r.children),
        }));
      };
      return getTOC(this.toc);
    },
    doms() {
      let doms = [];
      let getDoms = (toc = []) => {
        for (const item of toc) {
          let dom = document.getElementById(item.anchor);
          doms.push(dom);
          if (item.children && item.children.length) {
            getDoms(item.children);
          }
        }
      };
      getDoms(this.toc);
      return doms;
    },
  },
  methods: {
    handleSelect(item) {
      location.hash = item.anchor;
    },
    setSelect(scrollDom) {
      // if(!scrollDom){
      //     return;
      // }
      this.activeAnchor = "";
      for (const dom of this.doms) {
        if (!dom) {
          continue;
        }
        let domTop = dom.getBoundingClientRect().top;
        let topArea = 100; // 规定区域的大小
        if (domTop >= 0 && domTop <= topArea) {
          //在规定的区域
          this.activeAnchor = dom.id;
        } else if (domTop > topArea) {
          // 在规定区域的下方
          return;
        } else {
          // 在规定区域的上方
          this.activeAnchor = dom.id;
        }
      }
    },
  },
};
</script>

<style scoped lang="less">
.blog-toc-container {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  h2 {
    margin: 0;
    font-size: 1em;
    font-weight: bold;
    letter-spacing: 2px;
  }
}
</style>